package com.seedeer.common.util;

import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.*;
import com.seedeer.framework.config.OSSConfig;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.DataSource;
import javax.activation.MimetypesFileTypeMap;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @program: bbc
 * @description:
 * @author: Mr.Wang
 * @create: 2020-04-22 17:00
 **/
@Component
public class OSSSingleUtil {

    private final static Logger logger = LoggerFactory.getLogger(OSSSingleUtil.class);

    @Autowired
    private OSSConfig config;

    private static OSSConfig ossConfig;

    @PostConstruct
    public void init() {
        this.ossConfig = config;
    }

    private OSSSingleUtil() {
    }


    /**
     * oss 工具客户端
     */
    private volatile static OSSClient ossClient = null;

    /**
     * 上传文件至阿里云 oss
     *
     * @param bucketName  阿里云 oss bucket 名称
     * @param ossUrl      阿里云资源访问 url (不包含具体资源名称部分)
     * @param inputStream 待上传文件流
     * @return
     */
    public static void upload(MultipartFile file, String fileName) throws Exception {
        initOSS();
        ossClient.putObject(ossConfig.getBucketName(), fileName, file.getInputStream());
    }


    /**
     * 根据文件名删除
     *
     * @param fileName
     */
    public static void delete(String fileName) {
        ossClient.deleteObject(ossConfig.getBucketName(), fileName);
    }


    /**
     * 初始化 oss 客户端
     *
     * @param ossEndpoint
     * @param ossAccessKeyId
     * @param ossAccessKeySecret
     * @return
     */
    private static OSSClient initOSS() {
        if (ossClient == null) {
            synchronized (OSSSingleUtil.class) {
                if (ossClient == null) {
                    ossClient = new OSSClient(ossConfig.getEndpoint(),
                            new DefaultCredentialProvider(ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret()),
                            new ClientConfiguration());
                }
            }
        }
        creatBuckt(ossClient);
        return ossClient;
    }


    /**
     * 创建oss  buckt
     *
     * @param ossClient
     */
    public static void creatBuckt(OSSClient ossClient) {
        String bucketName = ossConfig.getBucketName();
        boolean exists = ossClient.doesBucketExist(bucketName);
        if (!exists) {
            logger.debug("bucket: [" + bucketName + "]不存在, 创建并设置权限 PublicRead");
            CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketName);
            // 设置bucket权限为公共读，默认是私有读写
            createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
            // 设置bucket存储类型为低频访问类型，默认是标准类型
            createBucketRequest.setStorageClass(StorageClass.IA);
            ossClient.createBucket(createBucketRequest);
        }
    }


    /**
     * 获取上传到oss文件名
     *
     * @param multipartFile 上传文件
     * @return
     * @throws Exception
     */
    public static String save(MultipartFile multipartFile) throws Exception {
        String fileName = getUuidName(multipartFile.getOriginalFilename());
        upload(multipartFile, fileName);
        return fileName;
    }


    /**
     * 文件下载
     * @param fileName
     * @return
     * @throws IOException
     */
    public static OSSObject downLoad(String fileName) throws IOException {
        OSSObject ossObject = ossClient.getObject(ossConfig.getBucketName(), fileName);
        return ossObject;
    }

    private static String getUuidName(String name) {
        String uuid = IdUtil.simpleUUID();
        String newName = uuid;
        if (name != null && name.contains(".")) {
            String extension = StringUtils.substringAfterLast(name, ".");
            if (StringUtils.isNotEmpty(extension)) {
                newName = uuid + "." + extension;
            }
        }
        return newName;
    }
}
